﻿// Copyright 2012 Stuart Turner
// Licensed under the Apache License, Version 2.0 [http://www.apache.org/licenses/LICENSE-2.0]

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;

using Complete.Data.Internal;
using Complete.Data.Linq;
using Complete.Data.Support;

namespace Complete.Data
{
	public class CompleteContext
	{
		static CompleteContext()
		{
			DefaultNameMapper = new DefaultNameMapper();
		}

		public CompleteContext(DbConnection conn)
			: this(conn, DefaultNameMapper)
		{
		}

		public CompleteContext(DbConnection conn, INameMapper nameMapper)
		{
			_Provider = new CompleteQueryProvider(conn, this);
			_ObjectCache = new Dictionary<Tuple<string, object>, object>();
			NameMapper = nameMapper;
		}

		private readonly QueryProvider _Provider;
		internal QueryProvider Provider { get { return _Provider; } }

		protected CompleteTable<T> GetTable<T>()
		{
			return new CompleteTable<T>(this);
		}

		#region Name Mapper
		public static INameMapper DefaultNameMapper { get; set; }
		public INameMapper NameMapper { get; private set; }
		#endregion

		#region Caching
		private Dictionary<Tuple<string, object>, object> _ObjectCache;
		private object _DictionaryLock = new object();
		public object GetObject(ITableWithKey obj)
		{
			var type = obj.GetType().ToString();
			var key = obj.GetKeyValue();
			if (key == null)
				throw new ArgumentNullException("Object returned as key was null.");
			var index = Tuple.Create(type, key);

			lock (_DictionaryLock)
			{
				object newObj;
				if (_ObjectCache.TryGetValue(index, out newObj))
				{
					return newObj;
				}
				else
				{
					_ObjectCache.Add(index, obj);
					return obj;
				}
			}
		}
		#endregion
	}
}
